# frozen_string_literal: true

namespace :gems do
  # :nocov:
  namespace :error_tracking_open_api do
    desc 'Generate OpenAPI client for Error Tracking'
    task :generate do |task|
      # Configuration
      api_url = 'https://gitlab.com/gitlab-org/opstrace/opstrace/-/raw/main/go/pkg/errortracking/swagger.yaml'
      gem_name = 'error_tracking_open_api'
      module_name = 'ErrorTrackingOpenAPI' # Namespacing is not supported like `ErrorTracking::OpenAPI`
      docker_image = 'openapitools/openapi-generator-cli:v6.0.0'

      vendor_gem_dir = Pathname.new(root_directory)
      gem_dir = vendor_gem_dir / gem_name

      # Always start with a clean state.
      rm_rf(gem_dir)

      generate_gem(
        vendor_gem_dir: vendor_gem_dir,
        api_url: api_url,
        gem_name: gem_name,
        module_name: module_name,
        docker_image: docker_image
      )

      post_process(gem_dir: gem_dir, gem_name: gem_name, task: task)
    end

    def root_directory
      File.expand_path('../../gems', __dir__)
    end

    def generate_gem(vendor_gem_dir:, api_url:, gem_name:, module_name:, docker_image:)
      user_id = File.stat(vendor_gem_dir).uid

      Kernel.system('docker', 'run',
                    "--user=#{user_id}", '--rm', "--volume=#{vendor_gem_dir}:/code", docker_image,
                    'generate',
                    '--input-spec', api_url,
                    '--generator-name', 'ruby',
                    '--output', "/code/#{gem_name}",
                    "--additional-properties=moduleName=#{module_name}"
      )
    end

    def post_process(gem_dir:, gem_name:, task:)
      write_file(gem_dir / 'README.md') do |content|
        readme_banner(task) + content
      end

      write_file(gem_dir / 'LICENSE', license)
      write_file(gem_dir / "#{gem_name}.gemspec") do |content|
        replace_string(content, 'Unlicense', 'MIT')
        replace_string(content, /.*add_development_dependency 'rspec'.*/, '')
        replace_string(content, /(\.files\s*=).*/, '\1 Dir.glob("lib/**/*")')
        replace_string(content, /(\.test_files\s*=).*/, '\1 []')
      end

      # This is gem is supposed to be generated. No developer should change code.
      remove_entry_secure(gem_dir / 'Gemfile')
      # The generated code doesn't align well with `gitlab-styles` configuration.
      remove_entry_secure(gem_dir / '.rubocop.yml')
      remove_entry_secure(gem_dir / '.travis.yml')
      remove_entry_secure(gem_dir / 'git_push.sh')
      # The RSpec examples are stubs and have no value.
      remove_entry_secure(gem_dir / 'spec')
      remove_entry_secure(gem_dir / '.rspec')
    end

    def write_file(full_path, content = nil, &block)
      content ||= yield(File.read(full_path))

      File.write(full_path, content)
    end

    def replace_string(content, from, to)
      raise "#{from.inspect} not found" unless content.gsub!(from, to)

      content
    end

    def readme_banner(task)
      <<~BANNER
        # #{generated_by(task)}

        See https://gitlab.com/gitlab-org/gitlab/-/blob/master/doc/development/rake_tasks.md#update-openapi-client-for-error-tracking-feature

      BANNER
    end

    def generated_by(task)
      "Generated by `rake #{task.name}` on #{Time.now.strftime('%Y-%m-%d')}" # rubocop:disable Rails/TimeZone
    end

    def license
      year = [2022, Date.today.year].uniq.join('-')

      <<~LICENSE
        Copyright #{year} GitLab B.V.

        Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

        The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
      LICENSE
    end
  end
  # :nocov:
end
